package com.next.aap.server.tasks;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.next.aap.client.RegisterDeviceResponse;
import com.next.aap.messages.DeviceRegisteredMessage;
import com.next.aap.messages.NotificationMessage;
import com.next.aap.messages.TaskStatus;
import com.next.aap.server.controller.MessageSender;
import com.next.aap.server.services.AppService;

@Component
@Scope(value = "prototype")
public class RegisterDeviceTask implements Runnable {

	private String deviceRegId;
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	AppService appService;
	@Autowired
	private MessageSender messageSender;

	public void run() {
		if (deviceRegId == null || deviceRegId.trim().isEmpty()) {
			logger.warn("No Device Id provided for RegisterDeviceTask");
			return;
		}

		try {
			RegisterDeviceResponse registerDeviceResponse = appService.registerDevice(deviceRegId);

			if (TaskStatus.STATUS_COMPLETED
					.equals(registerDeviceResponse.getStatus()) || TaskStatus.STATUS_ALREADY_REGISTERED
					.equals(registerDeviceResponse.getStatus())) {
				// Now send the message to Client that registration is succesfull
				DeviceRegisteredMessage deviceRegisteredMessage = new DeviceRegisteredMessage();
				deviceRegisteredMessage.setDeviceRegId(deviceRegId);
				
				List<String> deviceList = new ArrayList<String>();
				deviceList.add(deviceRegId);
				messageSender.sendMessage(deviceRegisteredMessage,NotificationMessage.DEVICE_REGISTERED_MESSAGE, deviceList);
				logger.info("Message Sent Succesfully");
			}

		} catch (Exception e) {
			logger.error("Unable to register device {}", deviceRegId, e);
		}

	}

	public String getDeviceRegId() {
		return deviceRegId;
	}

	public void setDeviceRegId(String deviceRegId) {
		this.deviceRegId = deviceRegId;
	}

}
